iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
佛心分享-刷題不只是刷題

轉生理工組後從零開始的leetcode刷題系列 第 9

day-9[medium.2048]next greater numerically balanced number

  • 分享至 

  • xImage
  •  

An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.

Given an integer n, return the smallest numerically balanced number strictly greater than n.


  • numerically=數值地
  • occurrences=出現

題目大意是題目會給一個數字n,我們需要找到比n大的最小平衡數字

  • 平衡數字:數字d在數字n中出現d次,那數字n就是一個平衡數字(如22,1333...)

我的解題思路:

  1. 從n+1開始逐個檢查
  2. 把數字X拆開來,然後統計出現次數
  3. 檢查到平衡數字後中斷迴圈並返回值

因為卡在把數字拆解的部分很~久,所以最後有借助AI之力!

class Solution {
public static boolean isBalanced(int x) {
// 記錄數字0-9的出現次數
int[] count = new int[10];
// 記錄每個數字的出現次數 //有參考chatgpt
int temp = x;
while (temp > 0) {
int digit = temp % 10; // 取出最後一位數字
count[digit]++; // 更新對應的數字計數
temp /= 10; // 去掉最後一位
}
// 再次遍歷原數字,檢查是否滿足數字平衡的條件
temp = x;
while (temp > 0) {
int digit = temp % 10;
if (count[digit] != digit) {
return false;
}
temp /= 10;
}
return true;
}
public int nextBeautifulNumber(int n) {
int x = n + 1;
// 增加x,直到找到數值平衡的數字
while (!isBalanced(x)) {
x++;
}
return x;
}
}


丟去leetcode檢查答案!
https://ithelp.ithome.com.tw/upload/images/20240924/20169432mrw7gyrewx.png
通過!睡覺!


上一篇
day-8[medium.2012]sum of beauty in the array
下一篇
day-10[easy.2016]maximum difference between increasing elements
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言